<template>
  <div class="accounts-payable-detail">
    <!-- 查询条件区域 -->
    <div class="search-container">
      <div class="search-row">
        <div class="search-item">
          <span class="label">日期</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY/MM/DD"
          />
        </div>

        <div class="search-item">
          <span class="label">供应商</span>
          <el-select
            v-model="supplier"
            placeholder="请选择"
            class="search-select"
          >
            <el-option label="G00001 商品综合批发有限公司" value="G00001" />
            <el-option label="G00002 全小蜂食品贸易有限公司" value="G00002" />
            <el-option label="G00003 广州食品批发有限公司" value="G00003" />
            <el-option label="G00004 深圳食品加工有限公司" value="G00004" />
            <el-option label="G00005 食品零售供应商" value="G00005" />
          </el-select>
          <el-icon class="search-icon"><InfoFilled /></el-icon>
        </div>

        <div class="search-item">
          <span class="label">业务员</span>
          <el-select
            v-model="salesman"
            placeholder="请选择"
            class="search-select"
          >
            <el-option label="采购-小陈" value="小陈" />
            <el-option label="采购-小李" value="小李" />
            <el-option label="采购-小张" value="小张" />
          </el-select>
          <el-icon class="search-icon"><InfoFilled /></el-icon>
        </div>

        <div class="search-actions">
          <el-button @click="resetSearch" class="reset-btn">重置</el-button>
          <el-button type="primary" @click="doSearch">查询</el-button>
        </div>
      </div>

      <div class="search-row">
        <div class="search-item">
          <span class="label">供应商类别</span>
          <el-select
            v-model="supplierType"
            placeholder="请选择"
            class="search-select"
          >
            <el-option label="综合批发" value="wholesale" />
            <el-option label="零售" value="retail" />
            <el-option label="加工企业" value="processing" />
          </el-select>
        </div>

        <div class="search-checkbox">
          <el-checkbox v-model="hideNoDebtSuppliers"
            >不显示无欠款供应商</el-checkbox
          >
        </div>
      </div>
    </div>

    <!-- 报表标题区域 -->
    <div class="report-header">
      <div class="date-range-text">
        日期: {{ dateRange[0] }} 至 {{ dateRange[1] }}
      </div>
      <h2 class="report-title">应付账款明细表</h2>
      <div class="report-actions">
        <el-button type="primary" class="export-btn">导出</el-button>
        <el-dropdown class="print-btn">
          <el-button type="primary">
            打印
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>打印预览</el-dropdown-item>
              <el-dropdown-item>直接打印</el-dropdown-item>
              <el-dropdown-item>打印设置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="processedTableData"
      border
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      class="detail-table"
      :span-method="spanMethod"
    >
      <el-table-column prop="supplier" label="供应商" min-width="180" />
      <el-table-column prop="salesman" label="业务员" min-width="100" />
      <el-table-column prop="billDate" label="单据日期" min-width="120" />
      <el-table-column prop="billNo" label="单据编号" min-width="120" />
      <el-table-column prop="businessType" label="业务类型" min-width="120" />
      <el-table-column
        prop="increasePayable"
        label="增加应付款"
        min-width="120"
        align="right"
      />
      <el-table-column
        prop="increasePrepayment"
        label="增加预付款"
        min-width="120"
        align="right"
      />
      <el-table-column
        prop="payableBalance"
        label="应付款余额"
        min-width="120"
        align="right"
      />
      <el-table-column prop="remark" label="备注" min-width="100" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { InfoFilled, ArrowDown } from "@element-plus/icons-vue";
import dayjs from "dayjs";
// 日期范围
const dateRange = ref([
  dayjs().startOf('month').format('YYYY/MM/DD'), 
  dayjs().format('YYYY/MM/DD')                  
]);
// 查询条件
const supplier = ref("");
const salesman = ref("");
const supplierType = ref("");
const hideNoDebtSuppliers = ref(false);

// 表头样式
const headerCellStyle = {
  backgroundColor: "#f5f7fa",
  fontWeight: "bold",
  color: "#303133",
  textAlign: "center",
};

// 原始表格数据
const rawTableData = ref([
  // G00001 商品综合批发有限公司
  {
    supplier: "G00001 商品综合批发有限公司",
    salesman: "",
    billDate: "",
    billNo: "期初余额",
    businessType: "",
    increasePayable: "0.00",
    increasePrepayment: "0.00",
    payableBalance: "13,881.78",
    remark: "",
  },
  {
    supplier: "G00001 商品综合批发有限公司",
    salesman: "采购-小陈",
    billDate: "2025/10/05",
    billNo: "CG20251005001",
    businessType: "采购入库",
    increasePayable: "5,000.00",
    increasePrepayment: "0.00",
    payableBalance: "18,881.78",
    remark: "食品原料采购",
  },

  // G00002 全小蜂食品贸易有限公司
  {
    supplier: "G00002 全小蜂食品贸易有限公司",
    salesman: "",
    billDate: "",
    billNo: "期初余额",
    businessType: "",
    increasePayable: "0.00",
    increasePrepayment: "0.00",
    payableBalance: "16,446.44",
    remark: "",
  },
  {
    supplier: "G00002 全小蜂食品贸易有限公司",
    salesman: "采购-小李",
    billDate: "2025/10/10",
    billNo: "CG20251010001",
    businessType: "采购入库",
    increasePayable: "3,000.00",
    increasePrepayment: "0.00",
    payableBalance: "19,446.44",
    remark: "包装材料",
  },

  // G00003 广州食品批发有限公司
  {
    supplier: "G00003 广州食品批发有限公司",
    salesman: "",
    billDate: "",
    billNo: "期初余额",
    businessType: "",
    increasePayable: "0.00",
    increasePrepayment: "0.00",
    payableBalance: "9,555.65",
    remark: "",
  },

  // G00004 深圳食品加工有限公司
  {
    supplier: "G00004 深圳食品加工有限公司",
    salesman: "",
    billDate: "",
    billNo: "期初余额",
    businessType: "",
    increasePayable: "0.00",
    increasePrepayment: "0.00",
    payableBalance: "16,698.12",
    remark: "",
  },
  {
    supplier: "G00004 深圳食品加工有限公司",
    salesman: "采购-小张",
    billDate: "2025/10/15",
    billNo: "CG20251015001",
    businessType: "采购入库",
    increasePayable: "2,500.00",
    increasePrepayment: "0.00",
    payableBalance: "19,198.12",
    remark: "加工原料",
  },

  // G00005 食品零售供应商
  {
    supplier: "G00005 食品零售供应商",
    salesman: "",
    billDate: "",
    billNo: "期初余额",
    businessType: "",
    increasePayable: "0.00",
    increasePrepayment: "0.00",
    payableBalance: "12,634.70",
    remark: "",
  },
  {
    supplier: "G00005 食品零售供应商",
    salesman: "采购-小陈",
    billDate: "2025/10/20",
    billNo: "CG20251020001",
    businessType: "采购入库",
    increasePayable: "1,800.00",
    increasePrepayment: "0.00",
    payableBalance: "14,434.70",
    remark: "零售商品",
  },
]);

// 处理表格数据，添加小计和合计行
const processedTableData = computed(() => {
  const result = [];
  const supplierGroups = {};
  let totalPayableBalance = 0;

  // 按供应商分组
  rawTableData.value.forEach((item) => {
    if (!supplierGroups[item.supplier]) {
      supplierGroups[item.supplier] = [];
    }
    supplierGroups[item.supplier].push(item);
  });

  // 为每个供应商添加数据行
  Object.keys(supplierGroups).forEach((supplierName) => {
    const items = supplierGroups[supplierName];

    // 添加供应商数据行
    items.forEach((item, index) => {
      // 只在第一行显示供应商名称
      const row = { ...item };
      if (index > 0) {
        row.supplier = ""; // 后续行不显示供应商名称
      }
      result.push(row);
    });

    // 计算该供应商的小计
    const lastItem = items[items.length - 1];
    const supplierSubtotal = {
      supplier: supplierName, // 小计行也显示供应商名称
      salesman: "",
      billDate: "",
      billNo: "小计",
      businessType: "",
      increasePayable: sumColumn(items, "increasePayable"),
      increasePrepayment: sumColumn(items, "increasePrepayment"),
      payableBalance: lastItem.payableBalance,
      remark: "",
      isSummary: true,
      isSubtotal: true, // 标记为小计行
    };

    result.push(supplierSubtotal);
    totalPayableBalance += parseFloat(
      lastItem.payableBalance.replace(/,/g, "")
    );
  });

  // 添加合计行
  const totalRow = {
    supplier: "",
    salesman: "",
    billDate: "",
    billNo: "合计",
    businessType: "",
    increasePayable: sumColumn(rawTableData.value, "increasePayable"),
    increasePrepayment: sumColumn(rawTableData.value, "increasePrepayment"),
    payableBalance: totalPayableBalance.toLocaleString("zh-CN", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }),
    remark: "",
    isSummary: true,
    isTotal: true, // 标记为合计行
  };

  result.push(totalRow);

  return result;
});

// 合并单元格方法
const spanMethod = ({ row, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    // 供应商列
    if (row.isSubtotal || row.isTotal) {
      // 小计和合计行不合并
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    if (row.supplier) {
      // 计算相同供应商的行数（不包括小计行）
      const supplierName = row.supplier;
      let rowspan = 1;

      // 查找后续行中属于同一供应商的行
      for (let i = rowIndex + 1; i < processedTableData.value.length; i++) {
        const currentRow = processedTableData.value[i];
        if (currentRow.isSubtotal || currentRow.isTotal) {
          break;
        }
        if (
          currentRow.supplier === supplierName ||
          (currentRow.supplier === "" &&
            processedTableData.value[i - 1].supplier === supplierName)
        ) {
          rowspan++;
        } else {
          break;
        }
      }

      return {
        rowspan: rowspan,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};

// 辅助函数：计算列总和
const sumColumn = (items, column) => {
  const sum = items.reduce((total, item) => {
    const value = parseFloat(item[column].replace(/,/g, "")) || 0;
    return total + value;
  }, 0);

  return sum.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

// 单元格样式
const cellStyle = ({ row }) => {
  // 小计行样式
  if (row.isSubtotal) {
    return {
      backgroundColor: "#f0f7ff",
      fontWeight: "bold",
    };
  }
  // 合计行样式
  if (row.isTotal) {
    return {
      backgroundColor: "#fff8e6",
      fontWeight: "bold",
    };
  }
  // 期初余额行样式
  if (row.billNo === "期初余额") {
    return {
      backgroundColor: "#f9f9f9",
    };
  }
  return;
};

// 查询操作
const doSearch = () => {
  // 这里实现查询逻辑
  console.log("查询条件:", {
    dateRange: dateRange.value,
    supplier: supplier.value,
    salesman: salesman.value,
    supplierType: supplierType.value,
    hideNoDebtSuppliers: hideNoDebtSuppliers.value,
  });
  // 实际项目中这里应该调用API获取数据
};

// 重置查询条件
const resetSearch = () => {
  dateRange.value = ["2025/10/01", "2025/10/24"];
  supplier.value = "";
  salesman.value = "";
  supplierType.value = "";
  hideNoDebtSuppliers.value = false;
};
</script>

<style scoped>
/* 基础样式 */
.accounts-payable-detail {
  padding: 15px;
  background-color: #fff;
  min-height: 100vh;
}

/* 查询区域样式 */
.search-container {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
}

.search-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  width: 90px;
  text-align: right;
  margin-right: 10px;
  color: #606266;
}

.search-select {
  width: 150px;
}

.search-icon {
  margin-left: -25px;
  color: #909399;
  cursor: pointer;
}

.search-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.reset-btn {
  color: #606266;
  background-color: #f5f5f5;
}

.search-checkbox {
  margin-left: 80px;
  display: flex;
  align-items: center;
}

/* 报表标题区域 */
.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.date-range-text {
  color: #606266;
  font-size: 14px;
}

.report-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: bold;
}

.report-actions {
  display: flex;
  gap: 10px;
}

.export-btn {
  background-color: #1890ff;
}

.print-btn {
  background-color: #409eff;
}

/* 表格样式 */
.detail-table {
  width: 100%;
  margin-bottom: 15px;
}

/* 金额列样式 */
:deep(.el-table .cell.right-align) {
  text-align: right;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: #ddd;
  border-radius: 3px;
}

:deep(.el-table .el-table__row.summary-row) {
  background-color: #f8f8f8 !important;
  font-weight: bold;
}

:deep(.el-table .el-table__row.summary-row:hover > td) {
  background-color: #fff4bf !important;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}
</style>